package com.ultrapower.ctool.view;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ultrapower.ctool.ConfUtils;
import com.ultrapower.ctool.bean.JingYingVO;
import com.ultrapower.ctool.bean.SearchTestBean;
import com.ultrapower.ctool.core.CustomApplication;
import com.ultrapower.ctool.model.RegisterRolePirVO;
import com.ultrapower.ctool.xn_app.JingYingActivity;
import com.ultrapower.ctool.xn_app.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by ctool on 2017/5/10.
 */

public class JingYingPopWindow extends PopupWindow implements SearchView.SearchViewListener {
    private View contentView;//页面
    private Context context;//上下文
    private View noView;
    JingYingActivity activity;
   // private CustomApplication application;
   // private CustomApplication application;
    private EditText companyName;//单位名称
    private Spinner enttype;//单位分类
    private Spinner mainenttype;//单位类型
    private JingYingVO jyVO;//参数
    private String wgName;
    private  String wgIdSearch;
    private  String wgId;
    private AutoCompleteTextView autoComplete;
    private SearchView searchView;//搜索view
    private ArrayAdapter<String> autoCompleteAdapter;//自动补全列表adapter
    private List<SearchTestBean> dbData;//数据库数据，总数据
    private List<String> autoCompleteData;//搜索过程中自动补全数据
    private static int DEFAULT_HINT_SIZE = 5;//默认提示框显示项的个数

    private static int hintSize = DEFAULT_HINT_SIZE;//提示框显示项的个数

    public static void setHintSize(int hintSize) {//设置提示框显示项的个数
        JingYingPopWindow.hintSize = hintSize;
    }

    private TextView filterReset;//重置
    private TextView filterSure;//确定
    //private OkHttpClient client = new OkHttpClient();
    private Gson gson = new Gson();
    Map <String,SearchTestBean>dbMap=new HashMap<String,SearchTestBean>();
    private CustomApplication application;
    private AdapterView.OnItemSelectedListener OnCatSpinnerCL = new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            ((TextView) parent.getChildAt(0)).setTextColor(Color.BLACK);
            ((TextView) parent.getChildAt(0)).setTextSize(18);
        }

        public void onNothingSelected(AdapterView<?> parent) {

        }
    };

    public JingYingPopWindow(Activity context, final Handler handler, CustomApplication application, JingYingActivity activity) {
        this.application=application;
        this.context = context;
        this.activity=activity;
        initData();
        initViews(handler);
    }

    /**
     * 初始化视图
     */
    private void initViews(final Handler handler) {


        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);//加载布局
        contentView = inflater.inflate(R.layout.popup_jingying_details, null);//弹框界面
        searchView = (SearchView) contentView.findViewById(R.id.jy_search_grid);
        //设置监听
         searchView.setSearchViewListener(this);
        //设置adapter
      // searchView.setTipsHintAdapter(hintAdapter);
        searchView.setAutoCompleteAdapter(autoCompleteAdapter);
        noView = contentView.findViewById(R.id.popup_jingying_noview);//关闭弹框
        companyName = (EditText) contentView.findViewById(R.id.company_name);
        enttype = (Spinner) contentView.findViewById(R.id.enttype);
        mainenttype = (Spinner) contentView.findViewById(R.id.mainenttype);
        filterReset = (TextView) contentView.findViewById(R.id.filter_reset);//重置
        filterSure = (TextView) contentView.findViewById(R.id.filter_sure);//确定
        noView.setOnClickListener(new CancelOnClickListener());
        contentView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
                    dismiss();
                }
                return true;
            }
        });


        // 重置的点击监听，将所有选项全设为false
        filterReset.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                companyName.setText("");
                wgName="";
                searchView.getEtInput().setText("");
                searchView.getIvDelete().setVisibility(View.GONE);
            }
        });
        // 确定的点击监听，将所有已选中项列出
        filterSure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String companyNameStr = companyName.getText().toString().trim();
                jyVO = new JingYingVO();
                if (!"".equals(wgName)) {
                    jyVO.setWgName(wgName);
                }
                if (!"".equals(companyNameStr)) {
                    jyVO.setCompanyName(companyNameStr);
                }
                if(enttype.getSelectedItem()!=null) {
                    jyVO.setEnttype(((RegisterRolePirVO) enttype.getSelectedItem()).getId());
                }
                if(mainenttype.getSelectedItem()!=null) {
                    jyVO.setMainenttype(((RegisterRolePirVO) mainenttype.getSelectedItem()).getId());
                }
                jyVO.setWgId(wgIdSearch);
                System.out.println(jyVO);
                Message msg = new Message();
                Bundle data = new Bundle();
                data.putSerializable("jyVO", jyVO);
                msg.setData(data);
                msg.what = 1;
                handler.sendMessage(msg);
                dismiss();
            }
        });

        this.setContentView(contentView);
        this.setWidth(ActionBar.LayoutParams.MATCH_PARENT);
        this.setHeight(ActionBar.LayoutParams.MATCH_PARENT);
        ColorDrawable dw = new ColorDrawable(00000000);
        this.setBackgroundDrawable(dw);
        this.setFocusable(true);
        this.setOutsideTouchable(false);
        this.update();

    }

    public class CancelOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            dismiss();
        }
    }

    public boolean onKeyDown(Context context, int keyCode, KeyEvent event) {
        this.context = context;
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            dismiss();
        }
        return true;
    }

    public void showFilterPopup(View parent) {
        if (!this.isShowing()) {
            this.showAsDropDown(parent);
        } else {
            this.dismiss();
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        //从数据库获取数据
        getDbData();
        //初始化自动补全数据
        getAutoCompleteData(null);
    }

    /**
     * 获取db 数据
     */
    private void getDbData() {
        System.out.println("-----------------------0");
        dbData = new ArrayList<>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("field", "gid")
                            .add("code", "c_aj_jydw")
                            .add("userId", String.valueOf(application.getLoginUser().getLogin_id()))
                            .build();
                    Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "widget/findJson").post(requestBody).build();
                    Response response = null;

                    response = client.newCall(request).execute();

                    if (response.isSuccessful()) {//成功
                        String result = response.body().string();
                        Map<String, Object> resultMap = gson.fromJson(result, Map.class);
                        // 初始数据库表
                        List<Map<String, Object>> list = (List<Map<String, Object>>) resultMap.get("rows");
                        for (Map<String, Object> li : list) {
                            SearchTestBean searchTestBean=     new SearchTestBean((String) li.get("xid"), (String) li.get("aname"), "", "");
                            dbData.add(searchTestBean);
                            dbMap.put((String) li.get("aname"),searchTestBean);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }}).start();



//        for (int i = 0; i < size; i++) {
//            dbData.add(new SearchTestBean(123, "android开发必备技能" + (i + 1), "Android自定义view——自定义搜索view", i * 20 + 2 + ""));
//        }
        //// TODO: 2017/5/13  没找到 R.id.autoCompleteText
        /*
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View mView = inflater.inflate(R.layout.popup_jingying_details, null);

        autoComplete=(AutoCompleteTextView)mView.findViewById(R.id.jywgText);

        wgAdater = new WGAdater(activity, R.layout.simple_dropdown_item_1line, null, "cn", android.R.id.text1);
        //// TODO: 2017/5/13 报错
        System.out.println(autoComplete);
        autoComplete.setThreshold(1);
        autoComplete.setAdapter(wgAdater);
        */
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //生产单位分类
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "widget/comboJson/c_aj_jydw-mainenttype?userId=" + String.valueOf(application.getLoginUser().getLogin_id())).build();
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {//成功
                        String result = response.body().string();
                        final List<RegisterRolePirVO> types = gson.fromJson(result, new TypeToken<List<RegisterRolePirVO>>() {
                        }.getType());
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ArrayAdapter<RegisterRolePirVO> aradapter = new ArrayAdapter<RegisterRolePirVO>(context, android.R.layout.simple_spinner_item, types);
                                aradapter.setDropDownViewResource(R.layout.simple_dropdown_item_1line);
                                mainenttype.setAdapter(aradapter);
                                mainenttype.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                                        ((TextView) parent.getChildAt(0)).setTextColor(Color.BLACK);
                                        ((TextView) parent.getChildAt(0)).setTextSize(18);
                                        RegisterRolePirVO item = (RegisterRolePirVO) mainenttype.getSelectedItem();
                                        final String mainenttypeId = (String) item.getId();
                                        if (mainenttypeId != null && !"".equals(mainenttypeId)) {
                                            //生产单位分类
                                            new Thread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    try {
                                                        OkHttpClient client = new OkHttpClient();
                                                        RequestBody enttypeRequestBody = new FormBody.Builder()
                                                                .add("exp", "select tid ID, tname CN from dt_dwtype where tlevel=3 and ptid =" + mainenttypeId)
                                                                .add("userId", String.valueOf(application.getLoginUser().getLogin_id()))
                                                                .build();
                                                        Request enttypeRequest = new Request.Builder().url(ConfUtils.SERVICE_URL + "widget/comboJson").post(enttypeRequestBody).build();
                                                        Response enttyperesponse = client.newCall(enttypeRequest).execute();
                                                        if (enttyperesponse.isSuccessful()) {//成功
                                                            String result = enttyperesponse.body().string();
                                                            final List<RegisterRolePirVO> enttypereses = gson.fromJson(result, new TypeToken<List<RegisterRolePirVO>>() {
                                                            }.getType());
                                                            System.out.println(enttypereses);

                                                            activity.runOnUiThread(new Runnable() {
                                                               @Override
                                                               public void run() {
                                                                    ArrayAdapter<RegisterRolePirVO> enttyperesaradapter = new ArrayAdapter<RegisterRolePirVO>(context, android.R.layout.simple_spinner_item, enttypereses);
                                                                    enttyperesaradapter.setDropDownViewResource(R.layout.simple_dropdown_item_1line);
                                                                    enttype.setAdapter(enttyperesaradapter);
                                                                    enttype.setOnItemSelectedListener(OnCatSpinnerCL);
                                                                }
                                                            });
                                                        }
                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                            }).start();
                                       }
                                    }

                                    public void onNothingSelected(AdapterView<?> parent) {
                                    }
                                });
                           }
                        });
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }

    /**
     * 获取自动补全data 和adapter
     */
    private void getAutoCompleteData(String text) {
        if (autoCompleteData == null) {
            //初始化
            autoCompleteData = new ArrayList<>(hintSize);
        } else {
            // 根据text 获取auto data
            autoCompleteData.clear();
            for (int i = 0, count = 0; i < dbData.size()
                    && count < hintSize; i++) {
                //System.out.println(dbData.get(i));
                if (dbData.get(i).getTitle()!=null&&dbData.get(i).getTitle().contains(text.trim())) {
                    autoCompleteData.add(dbData.get(i).getTitle());
                    count++;
                }
            }
        }
        if (autoCompleteAdapter == null) {
            autoCompleteAdapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, autoCompleteData);
        } else {
            autoCompleteAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 当搜索框 文本改变时 触发的回调 ,更新自动补全数据
     *
     * @param text
     */
    @Override
    public void onRefreshAutoComplete(String text) {
        //更新数据
        getAutoCompleteData(text);
    }

    /**
     * 点击搜索键时edit text触发的回调
     *
     * @param text
     */
    @Override
    public void onSearch(String text) {

        wgName = text;
        SearchTestBean searchBean =  dbMap.get(text);
        if (searchBean!=null)
        wgIdSearch=searchBean.getIconId();
    }
}
